package tts;

import javazoom.jl.player.Player;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * 文字转语音
 * @author Arnold Yand
 * @since 2018/8/22
 */
public class TextToSpeech {

  /**
   * http://dict.youdao.com/dictvoice?audio={text}
   * tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=
   */
  private static final String BAIDU_TTS = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=5&text=%s";

  private Player player = null;

  public TextToSpeech() throws Exception {
    play(textToSpeech("中华人民共和国"));
    System.out.println("play completed.");
  }

  public static void main(String[] args) throws Exception {
    new TextToSpeech();
  }

  private InputStream urlToSpeech(String url){
    return null;
  }

  private InputStream textToSpeech(String text) throws Exception {
    return transfer(text);
  }

  private InputStream transfer(String content) throws Exception {
    URL url = new URL(String.format(BAIDU_TTS, URLEncoder.encode(content, "UTF-8")));
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Charset", "UTF-8");
    urlConnection.connect();
    int responseCode = urlConnection.getResponseCode();
    if(responseCode == 200){
      return urlConnection.getInputStream();
    }

    throw new Exception("转换失败");
  }

  /**
   * 播放媒体文件
   *
   * @param data
   */
  private void play(InputStream data) throws Exception {
    player = new Player(data);
    player.play();
    while (!player.isComplete()) {
      TimeUnit.SECONDS.sleep(2);
    }
  }

  private void close(){
    if(player != null){
      player.close();
    }
  }
}
